﻿using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using MyERP.Services;
using Newtonsoft.Json.Linq;
using System.Security.Claims;

namespace MyERP.Controllers
{
    /// <summary>
    /// 登陆控制器
    /// </summary>
    public class LoginController : Controller
    {
        private readonly JwtHelper _jwtHelper;
        private readonly MyDbContext db;
        public LoginController(JwtHelper jwtHelper, MyDbContext db)
        {
            _jwtHelper = jwtHelper;
            this.db = db;
        }
        /// <summary>
        /// 登陆视图
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult Index()
        {
            return View();
        }
        /// <summary>
        /// 退出视图
        /// </summary>
        /// <returns></returns>
        public async Task<IActionResult> Logout()
        {
            // 清除认证 Cookie
            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            // 可以重定向到主页或其他页面
            return Redirect("/");
        }
        /// <summary>
        /// 登陆验证
        /// </summary>
        /// <param name="lm"></param>
        /// <returns></returns>
        [HttpPost]
        public IActionResult Login([FromBody] loginModel lm)
        {
            // 从 Session 中获取验证码
            var storedCaptcha = HttpContext.Session.GetString("CaptchaCode");

            // 验证验证码
            if (lm.captcha != storedCaptcha)
            {
                return Ok(new { success = false, message = "验证码错误" });
            }

            //验证账户密码
            var user = db.Users.FirstOrDefault(u => u.Name == lm.username);
            //如果用户名不存在或密码为空，返回信息
            if (user == null || user.Password != lm.password) 
            {
                return Ok(new { success = false, message = "用户名或密码错误" });
            }

            //将用户名存储在会话中
            HttpContext.Session.SetString("username", lm.username);
            //创建身份和声明
            var claimsIdentity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, lm.username));

            //如果拥有所有权限，设置为admin
            if (user.q1 == 1 && user.q2 == 1 && user.q3 == 1 && user.q4 == 1)
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "admin"));
            }
            //首页权限
            if (user.q1 == 1)
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "q1"));
            }
            //采购权限
            if (user.q2 == 1)
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "q2"));
            }
            //销售权限
            if (user.q3 == 1)
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "q3"));
            }
            //收支权限
            if (user.q4 == 1)
            {
                claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, "q4"));
            }

            //创建主体并标记该用户是经过认证的
            var claimPrincipal = new ClaimsPrincipal(claimsIdentity);
            // 设置持久化登录（设置过期时间为7天）
            var authProperties = new AuthenticationProperties
            {
                IsPersistent = true, // 允许持久化登录
                ExpiresUtc = DateTime.UtcNow.AddDays(7) // 设置过期时间为7天
            };
            HttpContext.SignInAsync(claimPrincipal,authProperties);

            return Ok(new { success = true, message = "登录成功", user});
        }
    }
    public class loginModel
    {
        public string username { get; set; }
        public string password { get; set; }
        public string captcha { get; set; }
    }
}
